const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            nodeKey1: '',
            nodeKey2: '',
            nodeKey3: '',
            nodeKey4: '',
            dataForm:{
                Check_In_Notice:'',
                Room_Category_SerialNumber:[]
            }, 
            blue_plate: [],
            image_category: [],
            window_type: [],
            room_facility_type: [],
            childDataForm1: [{}],
            childDataForm2: [],
            blue_plate_house_room: [],
            House_Room_SerialNumber:[],
            first:true,
            room_category:[]
        };
    },
    mounted() {
        let ls_URL = window.location.href;
        this.dataForm.Merchant_SerialNumber = getQueryObject(ls_URL, "nodeKey1");// 获取 nodeKey 参数
        this.dataForm.Merchant_Mapping_Blue_Plate_SerialNumber = getQueryObject(ls_URL, "nodeKey2");// 获取 nodeKey 参数
        this.dataForm.Merchant_Category_SerialNumber = getQueryObject(ls_URL, "nodeKey3");// 获取 nodeKey 参数
        this.dataForm.Blue_Plate_SerialNumber = getQueryObject(ls_URL, "nodeKey4");// 获取 nodeKey 参数
        this.getCategory();
    },
    watch: {
        childDataForm2(val) {
            if (this.action == 'Modify' && this.first) {
                this.first = false;
                this.House_Room_SerialNumber = val.filter(i => i.Row_Status != "1").map(i => i.House_Room_SerialNumber);
            }
        },
    },
    methods: {
        getData(nodeKey) {//查询
            const that = this;
            //获取对应子表表单对象
            let lJSONObject_Children = new Array();
            let lJSONObject_ChildData = new Object();
            try {
                //可能涉及多个子表
                document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                    let lJSONObject_ChildData_Options = new Object();
                    lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                    let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                    let ls_ChildDataForm = lJSONObject_ChildData_Options.form;

                    lJSONObject_ChildData[ls_ChildTableName] = ls_ChildDataForm;
                    lJSONObject_Children[ls_ChildTableName] = 'ChildTable';
                })
            } catch (error) { }
            //获得对应表单对象
            try {
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_TableName = lJSONObject_Data_Options.TableName;
                let ls_primary_key = lJSONObject_Data_Options.primary_key

                let lJSONObject_Data = new Object();
                lJSONObject_Data[ls_TableName] = ls_DataForm;
                lJSONObject_Data = { ...lJSONObject_Data, ...lJSONObject_ChildData };

                let lJSONObject_TableName = new Object();
                lJSONObject_TableName[ls_TableName] = 'MainTable'
                lJSONObject_TableName = { ...lJSONObject_TableName, ...lJSONObject_ChildData };
                for (let key in lJSONObject_TableName) {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                        method: "post",
                        data: {
                            Data: key,
                            Condition: `${ls_primary_key}='${nodeKey}'`,
                        },
                        success: (res) => {
                            if (lJSONObject_TableName[key] == 'MainTable') {
                                res[0].Room_Category_SerialNumber = res[0].Room_Category_SerialNumber? res[0].Room_Category_SerialNumber.split(','):[];
                                that[lJSONObject_Data[key]] = res[0];
                            } else {
                                that[lJSONObject_Data[key]] = res;
                            }
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest)
                        },
                    });
                }
            } catch (error) { }
        },
        changeRoom(val){
            if (val.length > parseInt(this.dataForm.Room_Quantity)) {
                val.pop();
                this.$message({
                    type:'warning',
                    message:'当前已选择适用房间数不能大于该房型房间数！'
                })
            }
        },
        getCategory() {
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'image_category',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.image_category = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'window_type',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.window_type = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryForObtainingTrees`,
                type: "GET",
                data: {
                    TableName: 'room_facility_type',
                    NodeCode: "",
                },
                success: (data) => {
                    this.room_facility_type = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: 'room_category',
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.room_category = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            console.log(this.dataForm.Blue_Plate_SerialNumber + "," + this.nodeKey);
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
                method: "post",
                data: {
                    SQLSerialNumber: 'f_blue_plate_house_room',
                    Condition: window.btoa(unescape(encodeURIComponent(this.dataForm.Blue_Plate_SerialNumber))),
                    ExtensionCondition: window.btoa(unescape(encodeURIComponent(this.nodeKey ? ("AND room_type_detail.Room_Type_SerialNumber <> '"+this.nodeKey+"'") :""))),
                },success: (data) => {
                   
                    this.blue_plate_house_room = data;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                }
            })
            // $.ajax({
            //     headers: requestHeaders(),
            //     url: `${mh}/generalBusiness/generalQueryByTableName`,
            //     method: "post",
            //     data: {
            //         Data: 'blue_plate_house_room',
            //         Condition: "Row_Status='0' AND Blue_Plate_SerialNumber = '" + this.dataForm.Blue_Plate_SerialNumber + "' AND blue_plate_house_room.House_Room_SerialNumber NOT IN (\r\n"
            //            + "SELECT DISTINCT House_Room_SerialNumber\r\n"
            //            + "FROM room_type_detail\r\n"
            //            + "WHERE Row_Status = '0'\r\n"
            //            + "AND room_type_detail.Room_Type_SerialNumber <> '"+ this.nodeKey +"')",
            //     },
            //     success: (data) => {
            //         this.blue_plate_house_room = data;
            //     },
            //     complete: (XMLHttpRequest) => {
            //         requestPretreatment(XMLHttpRequest)
            //     }
            // })
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (this.House_Room_SerialNumber.length != parseInt(this.dataForm.Room_Quantity)) {
                this.$message({
                    type:'warning',
                    message:'当前的房型房间数与选择适用房间数不一致！'
                })
                return 
            }
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                if (action == "Add") {
                    this.House_Room_SerialNumber.forEach(House_Room_SerialNumber => {
                        this.childDataForm2.push({
                            House_Room_SerialNumber,
                        });
                    });
                } else if (action == "Modify") {
                    this.House_Room_SerialNumber.forEach(House_Room_SerialNumber => {
                        let obj = this.childDataForm2.filter(i => i.House_Room_SerialNumber == House_Room_SerialNumber)[0];
                        if (obj) {
                            obj.Row_Status = "0";
                        } else {
                            this.childDataForm2.push({
                                Room_Type_SerialNumber: this.dataForm.Room_Type_SerialNumber,
                                House_Room_SerialNumber,
                            });
                        }
                    });
                    this.childDataForm2.forEach((item) => {
                        if (!this.House_Room_SerialNumber.some(i => i == item.House_Room_SerialNumber)) {
                            item.Row_Status = "1";
                        }
                    });
                }
                //没有子表下面内容就会报错，try/catch抛出异常
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        if (item.hasAttribute('data-options')) {
                            let lJSONObject_ChildData_Options = new Object();
                            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                            if (this[ls_DataForm][ls_primary_key]) {
                                this[ls_ChildDataForm].forEach(item => {
                                    item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                                })
                            }
                            //建立子表结构体
                            let JSONArray_ChildRecord = new Array();
                            JSONArray_ChildRecord = this[ls_ChildDataForm];
                            if (!this[ls_DataForm].Children) {
                                this[ls_DataForm].Children = new Object();
                            }
                            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                        }
                    })
                } catch (error) {

                }
                let dataForm = deepClone(this[ls_DataForm]);
                dataForm.Room_Category_SerialNumber = dataForm.Room_Category_SerialNumber.length > 0?dataForm.Room_Category_SerialNumber.join(","):''
                //建立新增提交结构
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        dataForm.Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(dataForm);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {
                    const { add, modify } = this.deal(dataForm);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    lJSONObject_DataSet['Add'] = new Object();
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        window.history.go(-1)
                    }
                    this.loading = false;
                })
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-text-editor', ylTextEditor);
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
